//
//  XMCameraAngleController.m
//  XiaoMiao
//
//  Created by 23 on 2018/2/6.
//  Copyright © 2018年 smallyou. All rights reserved.
//

#import "XMCameraAngleController.h"
#import "XMCameraAngleCell.h"
#import "XMCameraController.h"
#import "XMCameraNavigationController.h"
#import "XMCameraAngleModel.h"
#import "XMUploadPhotoModel.h"
#import "SuccessToOriginController.h"
#import "ConsumerCreatController.h"

@interface XMCameraAngleController () <UICollectionViewDelegate, UICollectionViewDataSource>

/**collectionView*/
@property(nonatomic,weak) UICollectionView *colectionView;

/**按钮*/
@property(nonatomic,weak) UIButton *nextButton;

/**datas*/
@property(nonatomic,strong) NSMutableArray <XMCameraAngleModel *>*datas;

@end

@implementation XMCameraAngleController

static NSString * const Id = @"angle";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setupUI];
    
    [self loadData];
}

#pragma mark - UI
- (void)setupUI
{
    self.title = @"拍摄角度选择";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (kScreenWidth - 10 * 2 - 15) / 2;
    CGFloat height = width * 3 / 4;
    layout.itemSize = CGSizeMake(width, height);
    layout.minimumInteritemSpacing = 0;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    collectionView.backgroundColor = [UIColor whiteColor];
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass(XMCameraAngleCell.class) bundle:nil] forCellWithReuseIdentifier:Id];
    [self.view addSubview:collectionView];
    self.colectionView = collectionView;
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.backgroundColor = kRGBColor(30, 177, 252);
    [nextButton setTitle:@"下一步" forState:UIControlStateNormal];
//    [nextButton addTarget:self action:@selector(actionNext) forControlEvents:UIControlEventTouchUpInside];
    [nextButton addTarget:self action:@selector(nextButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextButton];
    self.nextButton = nextButton;
    
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.nextButton.mas_top);
    }];
    
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XMCameraAngleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:Id forIndexPath:indexPath];
    
    XMCameraAngleModel *angle = self.datas[indexPath.item];
    cell.angle = angle;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //取出模型
    XMCameraAngleModel *angleModel = self.datas[indexPath.row];
//    if (angleModel.isPhotoed) {
//        [KLProgressHUD showPromptHUDWithMessage:@"当前角度已经拍照"];
//        return;
//    }
    
    WEAKSELF
    XMCameraController *vc = [[XMCameraController alloc] init];
    vc.standrandImageUrl = self.datas[indexPath.row].imageUrl;
    vc.callback = ^(UIImage *image) {
        
        angleModel.photoed = YES;
        angleModel.resultImage = image;
        [collectionView reloadData];
        
        
        //合并图片
        UIImage *standImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:weakSelf.datas[indexPath.row].imageUrl];
//        UIGraphicsBeginImageContext(CGSizeMake(image.size.width + standImage.size.width, image.size.height));
        UIGraphicsBeginImageContext(CGSizeMake(image.size.width + image.size.width, image.size.height));
        [standImage drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
        [image drawInRect:CGRectMake(image.size.width, 0, image.size.width, image.size.height)];
        UIImage *syncImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        angleModel.syncImage = syncImage;
        
        
    };
    XMCameraNavigationController *nav = [[XMCameraNavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - action
- (void)nextButtonDidClick
{
    if (self.datas.count == 0) {
        [KLProgressHUD showPromptHUDWithMessage:@"暂时无法上传照片"];
        return;
    }
    
    //判断图片是否都拍照OK
//    for (XMCameraAngleModel *angle in self.datas) {
//        if (!angle.isPhotoed) {
//            [KLProgressHUD showPromptHUDWithMessage:@"所有的角度都需要拍照"];
//            return;
//        }
//    }
    
//    if (self.isNewCamera) {
//        ConsumerCreatController *creat = [[ConsumerCreatController alloc] init];
//        [creat setUpCameraAngleModels:self.datas uploadPhotoModel:self.uploadModel];
//        [self.navigationController pushViewController:creat animated:YES];
//        return;
//    }
    
    
    //上传照片获取路径
    [self uploadImageRequest];
}

#pragma mark - data
- (void)loadData
{
    WEAKSELF
    [KLProgressHUD showWaitingHUDWithSuperView:self.view message:kLoadingMsg];
    [AppNetwork album_getCameraAngleWithCateId:self.uploadModel.cateId subCateId:self.uploadModel.subCateId subSubCateId:self.uploadModel.subSubCateId realName:self.uploadModel.baseInfoModel.realName completion:^(BOOL success, NSArray<XMCameraAngleModel *> *angles, AppError *error)
     {
         [KLProgressHUD hideHUDForView:weakSelf.view animated:YES];
         if (!success) {
             [KLProgressHUD showErrorHUDWithError:error];
             return;
         }
         
         for (XMCameraAngleModel *angle in angles) {
             angle.photoed = NO;
         }
         
         weakSelf.datas = [NSMutableArray arrayWithArray:angles];
         [weakSelf.colectionView reloadData];
    }];
}

//上传照片获取路径
- (void)uploadImageRequest
{
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"上传照片.."];
    
    //获取图片并上传
    dispatch_group_t group = dispatch_group_create();
    for (XMCameraAngleModel *angle in self.datas) {
        if (angle.photoed && (angle.resultImageUrl.length == 0)) {
            //取出图片
            UIImage *image = angle.resultImage;
            //上传图片
            dispatch_group_enter(group);
            
            [AppHttpClient userModule_uploadImage:image completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
                if (success) {
                    NSLog(@"----->上传成功");
                    angle.resultImageUrl = imageUrl;
                }
                [AppHttpClient userModule_uploadImage:angle.syncImage completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
                    if (success) {
                        NSLog(@"----->上传成功");
                        angle.syncImageUrl = imageUrl;
                    }
                    
                    dispatch_group_leave(group);
                }];
                
                
            }];
        }
    }
    
    WEAKSELF
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        progressHUD.hidden = YES;
        
        NSMutableArray <NSMutableDictionary *>*arrayM = [NSMutableArray array];
        for (XMCameraAngleModel *angle in self.datas) {
            if (angle.resultImageUrl.length && angle.photoed) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"imageUrl"] = angle.resultImageUrl;
                dict[@"templeId"] = angle.Id;
                dict[@"synthesisImageUrl"] = angle.syncImageUrl;
                [arrayM addObject:dict];
            }
        }
        
        NSError *error;
        NSData *date = [NSJSONSerialization dataWithJSONObject:arrayM options:NSJSONWritingPrettyPrinted error:&error];
        if (error) {
            NSLog(@"转换error：%@", error);
        }
        NSString *jsonStr = [[NSString alloc] initWithData:date encoding:NSUTF8StringEncoding];
        
        //完善上传模型
        weakSelf.uploadModel.photographUserAngleJson = jsonStr;
        
        //跳转到下一级
        [self savePhotoAndInfoRequest];
    });
}



// 保存照片和资料请求
- (void)savePhotoAndInfoRequest
{
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"保存中.."];
    
    WEAKSELF
    [AppNetwork album_uploadPhotoAndInfoWithModel:self.uploadModel completion:^(BOOL success, NSString *errorMsg) {
        progressHUD.hidden = YES;
        
        if (!success) {
            [KLProgressHUD showErrorHUDWithMessage:errorMsg];
            return;
        }
        
        [KLProgressHUD showSuccessHUDWithSuperView:nil message:@"保存成功" isHudEnable:YES completed:^{
            SuccessToOriginController *success = [[SuccessToOriginController alloc] init];
            [success setNavTitle:@"新建完成" desTitle:@"新建完成" btnTitle:@"返回查询"];
            [weakSelf.navigationController pushViewController:success animated:YES];
            
            [success setBtnClickHandle:^(SuccessToOriginController *btnVC) {
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            }];
        }];
    }];
}

#pragma mark - lazy
- (NSMutableArray *)datas
{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


@end
